package com.bicon.botu.finance.payment.weixin.utils;

import org.apache.http.NameValuePair;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.IOException;
import java.io.StringReader;
import java.util.*;

/**
 * Created by Robin on 2017/3/31.
 */
public class PayUtils {
    public static String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<" + params.get(i).getName() + ">");

            sb.append(params.get(i).getValue());
            sb.append("</" + params.get(i).getName() + ">");
        }
        sb.append("</xml>");

        return sb.toString();
    }

    public static String genPackageSign(List<NameValuePair> params, String key) {
        // 构造map
        Map<String,String> pmap = new HashMap<>(params.size());
        for (int i = 0; i < params.size(); i++) {
            pmap.put(params.get(i).getName(),params.get(i).getValue());
        }
        // 取key排序
        Set<String> keySet = pmap.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        // 拼接字符串
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals("sign")) {
                continue;
            }
            if (pmap.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(pmap.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);
        String packageSign = MD5Util.getMessageDigest(sb.toString().getBytes())
                .toUpperCase();

        return packageSign;
    }

    public static Map<String, String> decodeXml(String content)
    {
        SAXBuilder builder=new SAXBuilder(false);
        StringReader read = new StringReader(content);
        Map<String, String> xml = new HashMap<String, String>();
        try {
            Document doc = builder.build(read);
            Element element = doc.getRootElement();
            List list = element.getChildren();
            for (Iterator iter = list.iterator(); iter.hasNext();)
            {
                Element el =(Element) iter.next();
                xml.put(el.getName(), el.getText());
            }
            return xml;
        } catch (JDOMException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;

    }
    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }
}
